<template>
  <div>
    <Row>
      <Card>
        <Form ref="searchData" :model="searchData" :label-width="80">
          <Row>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="指标名称" prop="indexName">
                <Input
                  v-model="searchData.indexName"
                  suffix="ios-search"
                  placeholder="请输入指标名称"
                  style="width: auto"
                >
                  <Icon type="ios-search" slot="suffix" />
                </Input>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="选择年月" prop="dateTime">
                <DatePicker
                  type="date"
                  format="yyyyMM"
                  v-model="searchData.dateTime"
                  @on-change="handlerFormat"
                  placeholder="请选择指标日期"
                  style="width: auto"
                ></DatePicker>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="考核单位" prop="leadUnit">
                <Select filterable clearable placeholder="请选择考核单位" v-model="searchData.leadUnit">
                  <Option
                    v-for="item in getDepartmentList"
                    :value="item.departcode"
                    :key="item.departcode"
                  >{{ item.department }}</Option>
                </Select>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem>
                <Button
                  v-if="btnAccess.query"
                  type="primary"
                  :loading="searchLoading"
                  @click="searchSubmit(10,1)"
                >提交搜索</Button>
                <Button @click="submitReset('searchData')" style="margin-left:8px;">重置搜索</Button>
              </FormItem>
            </i-col>
          </Row>
        </Form>
      </Card>
    </Row>
    <Row style="margin-top:20px">
      <Card>
        <Table :loading="tabelLoading" :columns="tableHead" :data="tableData" border></Table>
        <div style="margin-top:20px;margin-left:35%">
          <Page
            @on-change="pageNumberChange"
            :page-size="pageSize"
            :total="pageTotal"
            @on-page-size-change="pageSizeChange"
            show-elevator
            show-sizer
          />
        </div>
      </Card>
    </Row>
    <!-- 添加 -->
    <Modal
      v-model="isrModal"
      :title="ModalTitles"
      :loading="ModalLoading"
      @on-cancel="cancelUserModal"
      :width="680"
    >
      <!-- <Row>
        <Table border :loading="tabelLoading" :columns="tableModalHead" :data="tableModalData"></Table>
        <div style="text-align:center;margin-top:30px;">
          <Page
            @on-change="pageNumberChange"
            :page-size="pageSize"
            :total="pageTotal"
            @on-page-size-change="pageSizeChange"
            show-elevator
            show-sizer
          />
        </div>
      </Row>-->

      <div slot="footer">
        <Button type="primary" size="large" :loading="ModalLoading" @click="submitUserModal">提交</Button>
        <Button size="large" @click="cancelUserModal">取消</Button>
      </div>
    </Modal>

    <!-- 侧边栏 -->
    <Drawer
      :title="drawerTitle"
      :mask-closable="false"
      @on-close="closeDrawerShow"
      :styles="styles"
      width="100%"
      v-model="isDrawerShow"
    >
      <Row>
        <Table
          height="500"
          border
          :loading="tabelLoading"
          :columns="tableModalHead"
          :data="tableModalData"
        ></Table>
        <div style="text-align:center;margin-top:30px;">
          <Page
            @on-change="pageNumberChange2"
            :page-size="pageSize"
            :total="pageTotal"
            @on-page-size-change="pageSizeChange2"
            show-elevator
            show-sizer
          />
        </div>
        <!-- Excel导入 -->
        <div style="margin-top:20px;">
          <Card title="导入EXCEL">
            <Row>
              <i-col :xs="24" :md="8" :lg="3">
                <Upload action :before-upload="handleBeforeUpload" accept=".xls, .xlsx">
                  <Button
                    icon="ios-cloud-upload-outline"
                    :loading="uploadLoading"
                    @click="handleUploadFile"
                  >选择文件</Button>
                </Upload>
              </i-col>
              <!-- <i-col :xs="24" :md="8" :lg="3">
            <DatePicker
              type="year"
              format="yyyy"
              v-model="formCountyList.dateTime"
              @on-change="updateTime"
              placeholder="请选择指标年份"
              style="width: auto"
            ></DatePicker>
              </i-col>-->
              <i-col :xs="24" :md="8" :lg="3">
                <Button type="primary" @click="updateExcel">上传分数</Button>
              </i-col>
              <i-col :xs="24" :md="8" :lg="3">
                <Button type="success" @click="downTownDataFc" style="margin:0 20px;">下载模板</Button>
              </i-col>
            </Row>
            <Row>
              <i-col :xs="24">
                <div>
                  <span style="color:red;font-size:18px;">*</span> 模板上传的数据为得分率，得分率为百分制，保留两位小数
                </div>
                <div>
                  <span style="color:red;font-size:18px;">*</span> 温馨小提示：
                  <br />1.上传分数前请先下载模板
                  <br />2.替换掉模板中原有的数据点击保存，注意表头和表头顺序都不能改，文件名是可修改
                  <br />3.点击"选择文件"，找到刚保存的模板后，点击"上传文件"按钮即可
                  <br />4.如上传数据有误，在原Excel模板中修改后保存，重新上传即可
                </div>
              </i-col>
            </Row>
            <Row>
              <div class="ivu-upload-list-file" v-if="file !== null">
                <Icon type="ios-stats"></Icon>
                {{ file.name }}
                <Icon
                  v-show="showRemoveFile"
                  type="ios-close"
                  class="ivu-upload-list-remove"
                  @click.native="handleRemove()"
                ></Icon>
              </div>
            </Row>
            <Row>
              <transition name="fade">
                <Progress v-if="showProgress" :percent="progressPercent" :stroke-width="2">
                  <div v-if="progressPercent == 100">
                    <Icon type="ios-checkmark-circle"></Icon>
                    <span>成功</span>
                  </div>
                </Progress>
              </transition>
            </Row>
          </Card>
          <Row class="margin-top-10">
            <Table :columns="tableTitle" :data="tableData1" :loading="tableLoading" height="500"></Table>
          </Row>
        </div>
      </Row>
    </Drawer>
  </div>
</template>
<script>
import excel from "@/libs/excel";
import { hasOneOf } from "@/libs/tools";
import { URL } from "@/libs/util";
import {
  unitAssessmentAjax,
  importUnitScoretAjax,
  countryIndexAjax
} from "@/api/countyUnit";
// 以防命名冲突
const HOST = URL;
// 删除URL
const DELETE_URL = "/countryUnitIndicators/delete";
// 修改URL
const UPDATE_URL = "/countryUnitIndicators/update";
// 添加URL
const INSERT_URL = "/countryUnitIndicators/insert";
// 查询URL
const QUERY_URL = "/countryUnitScore/query";
// 二级表格查询
const QUERY_URL2 = "/countryUnitScore/afterimport";

const INSERT_TITLE = "添加";
const UPDATE_TITLE = "编辑";
export default {
  data() {
    // 验证手机号码
    return {
      // 增删改查权限按钮
      btnAccess: {
        add: true,
        add2: "inline-block",
        del: "inline-block",
        upd: true,
        query: true
      },
      // 是否为超级管理员
      isSpuerAdmins: {
        query: true
      },
      isrModal: false, // 模态框
      searchLoading: false, // 搜索Loading
      ModalLoading: false, // 提交loading
      tabelLoading: false, // 表格loading
      ModalTitles: "", // 模态框title
      isResponsible: "",
      pageSize: 10,
      pageNumber: 1,
      pageTotal: 10,
      drawerTitle: "指标",
      isDrawerShow: false, // 侧边栏隐藏
      // 侧边栏样式
      styles: {
        height: "calc(100% - 55px)",
        overflow: "auto",
        paddingBottom: "53px",
        position: "static"
      },
      searchData: {
        leadUnit: "", // 考核单位
        indexName: "", // 指标名称
        dateTime: "" // 年份
      },
      tableData: [], // 表格数据
      tableHead: [
        {
          title: "序号",
          type: "index",
          width: 80,
          align: "center"
        },
        {
          title: "指标名称",
          key: "indexName"
        },
        {
          title: "考核单位",
          key: "leadUnit"
        },
        {
          title: "年份",
          key: "dateTime",
          width: 150
        },
        {
          title: "状态",
          key: "audit",
          width: 150,
          render: (h, params) => {
            const row = params.row;
            var color = "";
            var text = "";
            if (row.audit === "1") {
              color = "primary";
              text = "已填写";
            } else {
              color = "error"; // 未填写
              text = "未填写";
            }
            return h(
              "Tag",
              {
                props: {
                  color: color
                }
              },
              text
            );
          }
        },
        {
          title: "操作",
          key: "action",
          width: 160,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.isDrawerShow = true;
                      this.drawerTitle = params.row.indexName;
                      this.uploadId = params.row.id;
                      // 请求二级表格数据
                      this.formData2.id = params.row.id;
                      // 请求二级表格数据
                      this._getSecondtData(
                        this.formData2,
                        QUERY_URL2,
                        this.pageSize,
                        this.pageNumber
                      );
                    }
                  }
                },
                "查看或编辑分数"
              )
            ]);
          }
        }
      ],
      formData2: {
        id: ""
      }, // 二级表格参数
      tableModalHead: [
        {
          title: "被考核单位",
          key: "department",
          width: 350
        },
        {
          title: "1月",
          key: "month01",
          sortable: true
        },
        {
          title: "2月",
          key: "month02",
          sortable: true
        },
        {
          title: "3月",
          key: "month03",
          sortable: true
        },
        {
          title: "4月",
          key: "month04",
          sortable: true
        },
        {
          title: "5月",
          key: "month05",
          sortable: true
        },
        {
          title: "6月",
          key: "month06",
          sortable: true
        },
        {
          title: "7月",
          key: "month07",
          sortable: true
        },
        {
          title: "8月",
          key: "month08",
          sortable: true
        },
        {
          title: "9月",
          key: "month09",
          sortable: true
        },
        {
          title: "10月",
          key: "month10",
          sortable: true
        },
        {
          title: "11月",
          key: "month11",
          sortable: true
        },
        {
          title: "12月",
          key: "month12",
          sortable: true
        }
      ], // 表格模态框表头
      tableModalData: [], // 表格模态框数据
      // 上传表格
      uploadLoading: false,
      uploadId: "", // 上传时所需id值
      progressPercent: 0,
      showProgress: false,
      showRemoveFile: false,
      file: null,
      tableData1: [],
      tableTitle: [],
      tableLoading: false,
      UploadLoadingBtn: false
    };
  },
  methods: {
    // 搜索
    searchSubmit(pageSize, pageNumber) {
      this.searchLoading = true;
      this._getData(this.searchData, QUERY_URL, pageSize, pageNumber);
    },
    // 重置搜索
    submitReset(name) {
      this.searchLoading = false;
      this.$refs[name].resetFields();
    },
    // 搜索框年份
    handlerFormat(year) {
      this.searchData.dateTime = year;
    },
    // 删除用户
    deleteIndex(row) {
      if (this.accessAgent) {
        this.$Message.error("权限不足！");
        return;
      }
      this.$Modal.confirm({
        title: "删除此条信息",
        content: "<p>删除完成后将无法恢复</p>",
        loading: true,
        onOk: () => {
          this._addOrUpdate(row, DELETE_URL).then(result => {
            this.$Modal.remove();
            if (result.code === "200") {
              this.$Message.info("删除成功!");
              this._getData(
                this.tableData,
                QUERY_URL,
                this.pageSize,
                this.pageNumber
              );
            } else {
              this.$Message.error("删除失败！");
            }
          });
        }
      });
    },
    // 显示模态框
    showUserModal() {
      this.ModalTitles = "添加";
      this.isrModal = true;
    },
    // 提交
    submitUserModal() {
      this.$refs["indexMagement"].validate(valid => {
        if (valid) {
          this.ModalLoading = true;
          if (this.ModalTitles === INSERT_TITLE) {
            this._addOrUpdate(this.modalForms, INSERT_URL).then(result => {
              this.isrModal = false;
              this.ModalLoading = false;
              if (result.code === "200") {
                this.$Message.success("添加成功！");
                this._getData(
                  this.searchData,
                  QUERY_URL,
                  this.pageSize,
                  this.pageNumber
                );
              } else {
                this.$Message.error(result.message);
              }
            });
          } else if (this.ModalTitles === UPDATE_TITLE) {
            this._addOrUpdate(this.modalForms, UPDATE_URL).then(result => {
              this.isrModal = false;
              this.ModalLoading = false;
              if (result.code === "200") {
                this.$Message.success("添加成功！");
                this._getData(
                  this.searchData,
                  QUERY_URL,
                  this.pageSize,
                  this.pageNumber
                );
              } else {
                this.$Message.error("添加失败！");
              }
            });
          }
        } else {
          this.$Message.error("请填写完整！");
        }
      });
    },
    cancelUserModal() {
      this.isrModal = false;
    },
    // 页码
    pageNumberChange(pageNumber) {
      this.pageNumber = pageNumber;
      this._getData(this.searchData, QUERY_URL, this.pageSize, this.pageNumber);
    },
    // 页数
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this._getData(this.searchData, QUERY_URL, this.pageSize, this.pageNumber);
    },
    // 添加/修改
    _addOrUpdate(formData, url) {
      const keyOne = "countryUnitIndicatorsEntity";
      return new Promise((resolve, reject) => {
        unitAssessmentAjax({ formData, url, keyOne })
          .then(result => {
            if (result.data !== undefined) {
              resolve(result.data);
            } else {
              reject(err);
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    // 查询
    _getData(formData, url, pageSize, pageNumber) {
      this.tabelLoading = true;
      formData = Object.assign(formData, {
        pageSize,
        pageNumber
      });
      const keyOne = "countryUnitScoreFilter";
      unitAssessmentAjax({ formData, url, keyOne })
        .then(result => {
          this.tabelLoading = false;
          if (result.data.code === "200") {
            this.searchLoading = false;
            this.tableData = result.data.results.list;
            // this.pageTotal = result.data.results.pageTotal;
            this.$Message.success("查询成功");
          } else {
            this.$Message.error("查询失败");
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 二级表格查询
    _getSecondtData(formData, url, pageSize, pageNumber) {
      this.tabelLoading = true;
      formData = Object.assign(formData, {
        pageSize,
        pageNumber
      });
      const keyOne = "countryUnitScoreFilter";
      unitAssessmentAjax({ formData, url, keyOne })
        .then(result => {
          this.tabelLoading = false;
          if (result.data.code === "200") {
            this.searchLoading = false;
            this.tableModalData = result.data.results.list;
            // this.pageTotal = result.data.results.pageTotal;
            this.$Message.success("查询成功");
          } else {
            this.$Message.error("查询失败");
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 页码
    pageNumberChange2(pageNumber) {
      this.pageNumber = pageNumber;
      this._getSecondtData(
        this.formData2,
        QUERY_URL2,
        this.pageSize,
        this.pageNumber
      );
    },
    // 页数
    pageSizeChange2(pageSize) {
      this.pageSize = pageSize;
      this._getSecondtData(
        this.formData2,
        QUERY_URL2,
        this.pageSize,
        this.pageNumber
      );
    },
    // 关闭侧边栏
    closeDrawerShow() {
      this.isDrawerShow = false;
    },
    // 上传文件
    // Excel导入
    initUpload() {
      this.file = null;
      this.showProgress = false;
      this.loadingProgress = 0;
      this.tableData1 = [];
      this.tableTitle = [];
    },
    // 点击上传触发函数
    handleUploadFile() {
      this.initUpload();
    },
    // 删除Excel
    handleRemove() {
      this.initUpload();
      this.$Message.info("上传的文件已删除！");
    },
    handleBeforeUpload(file) {
      const fileExt = file.name
        .split(".")
        .pop()
        .toLocaleLowerCase();
      if (fileExt === "xlsx" || fileExt === "xls") {
        this.readFile(file);
        this.file = file;
      } else {
        this.$Notice.warning({
          title: "文件类型错误",
          desc:
            "文件：" +
            file.name +
            "不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。"
        });
      }
      return false;
    },
    // 读取文件
    readFile(file) {
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onloadstart = e => {
        this.uploadLoading = true;
        this.tableLoading = true;
        this.showProgress = true;
      };
      reader.onprogress = e => {
        this.progressPercent = Math.round((e.loaded / e.total) * 100);
      };
      reader.onerror = e => {
        this.$Message.error("文件读取出错");
      };
      reader.onload = e => {
        this.$Message.info("文件读取成功");
        const data = e.target.result;
        var { header, results } = excel.read(data, "array");
        header = header.slice(0, 27);
        var tableTitle = header.map((item, i) => {
          return { title: results[0][item], key: item };
        });
        // 验证表头
        const regExcel = err => {
          this.$Notice.error({
            title: "Excel格式错误",
            desc: 'Excel："' + err + '"   格式错误,请核对Excel模块。'
          });
          results = ""; // 表内容
          tableTitle = ""; // 表头
          this.uploadLoading = false;
          this.tableLoading = false;
          this.showRemoveFile = true;
        };

        // 对Excel行进处理 提醒用户是不是导入Excel模板错误
        for (let i = 0; i < tableTitle.length; i++) {
          if (tableTitle[i].key === "department") {
            if (tableTitle[i].title !== "被考核单位") {
              regExcel("被考核单位");
              return;
            }
          } else if (tableTitle[i].key === "score") {
            if (tableTitle[i].title !== "分数") {
              regExcel("分数");
              return;
            }
          } else {
            regExcel("上传模板有误，请从新上传");
            return;
          }
        }

        // 截取有效数据
        this.tableData1 = results.slice(1);
        this.tableTitle = tableTitle;
        this.uploadLoading = false;
        this.tableLoading = false;
        this.showRemoveFile = true;
      };
    },
    updateExcel() {
      // this.UploadLoadingBtn = true;
      if (!this.tableData1.length) {
        this.$Message.error("请选择上传文件");
        // this.UploadLoadingBtn = false;
        return;
      }
      // const fromIndexOne = { list: [] }; // 一级指标
      const formIndex = { list: [] }; // 指标
      // 处理二级指标
      let countyAllIndex = {};
      countyAllIndex["listScore"] = [];
      for (let i = 0; i < this.tableData1.length; i++) {
        let data1 = {
          department: this.tableData1[i]["department"],
          score: this.tableData1[i]["score"]
        };
        countyAllIndex["listScore"].push(data1);
        countyAllIndex["uploadId"] = this.uploadId;
      }
      // 根据后端要求 用户EXCEL上传的数据放在LIST里面
      formIndex["list"].push(countyAllIndex);
      this._importData(formIndex).then(res => {
        this.tableData1 = [];
        this.tableTitle = [];
        if (res.code === "200") {
          this.$Message.success(res.message);
          // 上传成功重新查询导入分数表格
          this._getSecondtData(
            this.formData2,
            QUERY_URL2,
            this.pageSize,
            this.pageNumber
          );
          // 上传成功重新刷新一级页面数据
          this._getData(
            this.searchData,
            QUERY_URL,
            this.pageSize,
            this.pageNumber
          );
        } else if (res.code === "500") {
          this.$Message.error({
            content: res.message,
            duration: 10,
            closable: true
          });
          this.tableData1 = [];
          this.tableTitle = [];
        }
      });
    },
    _importData(formData) {
      const url = "/countryUnitScore/importUnitScore";
      const keyOne = "countryUnitScoreFilter";
      return new Promise((resolve, reject) => {
        importUnitScoretAjax({ formData, url, keyOne }).then(res => {
          if (res.data.code === "200" || res.data.code === "500") {
            resolve(res.data);
          } else {
            reject(eer);
          }
        });
      });
    },
    /**
     * 下载县直单位分数上传模板
     */
    downTownDataFc() {
      window.open(HOST + "/countryUnitScore/exportExcelMould");
    }
  },
  mounted() {},
  created() {
    this._getData(this.searchData, QUERY_URL, this.pageSize, this.pageNumber);
    // 获取按钮权限
    let btnAccess = sessionStorage.getItem("btnaccess");
    this.globalFunction(btnAccess);
    // 获取是否为超级管理员权限
    let isSuperAdmin = sessionStorage.getItem("isSuperAdmin");
    this.globalFunction2(isSuperAdmin);
  },
  computed: {
    getDepartmentList() {
      return this.$store.state.user.departmentList;
    },
    getDepartment() {
      return this.$store.state.user.department;
    },
    access() {
      return this.$store.state.user.access;
    },
    // 管理员
    accessAdmin() {
      return hasOneOf(["admin"], this.access);
    },
    // 责任人
    accessRespons() {
      return hasOneOf(["responsible"], this.access);
    },
    // 经办人
    accessAgent() {
      return hasOneOf(["agent"], this.access);
    }
    //
  }
};
</script>
